package com.iwithlong.service.impl;

import com.github.qcloudsms.SmsMultiSender;
import com.github.qcloudsms.SmsMultiSenderResult;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.imesne.assistant.common.exception.ImesneException;
import com.imesne.assistant.common.utils.PropertyUtils;
import com.imesne.assistant.common.validation.Verifier;
import com.imesne.assistant.jdbc.persist.JdbcDao;
import com.iwithlong.context.Constants;
import com.iwithlong.entity.ProductSms;
import com.iwithlong.enums.IwithlongMsg;
import com.iwithlong.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * User : liulu
 * Date : 2017/6/20 16:02
 * version $Id: SmsServiceImpl.java, v 0.1 Exp $
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Resource
    private JdbcDao jdbcDao;

    private Integer appid =Integer.valueOf (PropertyUtils.getProperty("config", "sms.appid")) ;

    private String appkey = PropertyUtils.getProperty("config", "sms.appkey");

    private Integer tmplId=Integer.valueOf(PropertyUtils.getProperty("config", "sms.tmplId")) ;

    private Integer enrollTmplId=Integer.valueOf (PropertyUtils.getProperty("config", "sms.enrollTempId")) ;

    @Value("${god.pwd.key:0000000000}")
    private String godPwdKey;

    @Value("${god.pwd.enable:false}")
    private boolean godPwdEnable;



    @Override
    public void validateCode(HttpSession session, String code) {
        if (godPwdEnable && StringUtils.equals(code, godPwdKey)) {
            return;
        }
        if (!StringUtils.equals(StringUtils.trim(code), getSessionCode(session))) {
            throw new ImesneException(IwithlongMsg.VERIFICATION_CODE_ERROR);
        }
        session.removeAttribute(Constants.VERIFICATION_CODE);

    }

    @Override
    public String sendVerificationCode(String receiver) {
        Verifier.init()
                .notBlank(receiver, "手机号")
                .minLength(receiver, 11, "手机号")
                .maxLength(receiver, 11, "手机号")
                .validate();

        String code = getCode(6);

        log.info("mobile:{}", receiver);
        SmsSingleSenderResult smsSingleSenderResult=new SmsSingleSenderResult ();
        try {

            SmsSingleSender sender = new   SmsSingleSender(appid, appkey);
            ArrayList<String> params = new ArrayList<>();
            params.add(code);
            params.add("1");
            smsSingleSenderResult= sender.sendWithParam ("86", receiver, tmplId, params, "", "", "");


        } catch (Exception e) {
            log.error("发送短信出错",e);
        }

        if (smsSingleSenderResult.result!=0) {
            throw new ImesneException(smsSingleSenderResult.errMsg);
        }
        return code;
    }

    @Override
    public void sendActivityEnrollMessages(ArrayList<String> phoneNumbers, Long productSmsId) {
        ProductSms productSms = jdbcDao.get(ProductSms.class, productSmsId);
        String content = productSms.getContent();
        String[] messages=content.split("&");
        ArrayList<String> params = new ArrayList<>();
        for(int i=0;i<5;i++){
            params.add(messages[i]);
        }
        SmsMultiSenderResult smsMultiSenderResult=new SmsMultiSenderResult ();
        try {
            SmsMultiSender msender = new SmsMultiSender(appid, appkey);
            smsMultiSenderResult = msender.sendWithParam("86", phoneNumbers, enrollTmplId,
                    params, "", "", "");
        } catch (Exception e) {
            throw new ImesneException("发送短信时异常，无法审核");
        }

    }

    private String getCode(int length) {

        StringBuilder result = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            result.append(RandomUtils.nextInt(0, 10));
        }

        return result.toString();
    }


    @Override
    public String getSessionCode(HttpSession session) {
        return (String) session.getAttribute(Constants.VERIFICATION_CODE);
    }


}
